package com.example.word.ui.activity;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.dict.R;
import com.example.word.MyApplication;
import com.example.word.adapter.BrowseAdapter;
import com.example.word.adapter.UnitAdapter;
import com.example.word.adapter.WordStudyAdapter;
import com.example.word.bean.Browse;
import com.example.word.bean.Collect;
import com.example.word.bean.Dict;
import com.example.word.bean.StudyPlan;
import com.example.word.bean.Unit;
import com.example.word.bean.User;
import com.example.word.bean.Word;
import com.example.word.util.CommonUtils;
import com.example.word.util.DateUtils;
import com.example.word.util.HttpUtils;
import com.example.word.util.MessageUtils;
import com.example.word.util.SPUtils;
import com.example.word.widget.ActionBar;
import com.google.gson.Gson;

import org.litepal.crud.DataSupport;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 单词学习
 */
public class WordStudyActivity extends AppCompatActivity {
    private Activity myActivity;
    private ActionBar mTitleBar;//标题栏
    private LinearLayout operationList;
    private RecyclerView recyclerView;
    private WordStudyAdapter wordStudyAdapter;
    private List<Word> wordList = new ArrayList<>();
    public static String account;
    private Button nextWord, preWord;
    private int currentWordIndex;
    private MediaPlayer mediaPlayer;
    private ImageView collect, collect1;


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_word_study);
        myActivity = this;
        account = (String) SPUtils.get(myActivity, SPUtils.ACCOUNT, "");
        recyclerView = findViewById(R.id.rv_word_study_list);
        operationList = findViewById(R.id.operationList);
//        if ((Boolean) SPUtils.get(myActivity, SPUtils.IS_ADMIN, false)) {
//            operationList.setVisibility(View.GONE);
//        }
        mTitleBar = (ActionBar) findViewById(R.id.myActionBar);
        nextWord = findViewById(R.id.nextWord);
        nextWord.setText("下一个");
        preWord = findViewById(R.id.preWord);
        collect = findViewById(R.id.collect);
        collect1 = findViewById(R.id.collect1);
        mTitleBar.setData(myActivity, "单词学习", R.drawable.ic_back, 0, 0, getResources().getColor(R.color.colorPrimary), new ActionBar.ActionBarClickListener() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {
            }
        });
        // 设置主题
        if (!com.example.word.ui.activity.MainActivity.colorChange) {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
            nextWord.setBackground(getResources().getDrawable(R.drawable.btn_border_next2));
            preWord.setBackground(getResources().getDrawable(R.drawable.btn_border_next));
        } else {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.myColor));
            nextWord.setBackground(getResources().getDrawable(R.drawable.btn_border_next_my_color2));
            preWord.setBackground(getResources().getDrawable(R.drawable.btn_border_next_my_color));
        }
        initView();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initView() {
        account = (String) SPUtils.get(myActivity, SPUtils.ACCOUNT, "");
        LinearLayoutManager layoutManager = new LinearLayoutManager(myActivity);
        //=1.2、设置为垂直排列，用setOrientation方法设置(默认为垂直布局)
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //=1.3、设置recyclerView的布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //==2、实例化适配器
        //=2.1、初始化适配器
        wordStudyAdapter = new WordStudyAdapter(recyclerView);
        //=2.3、设置recyclerView的适配器
        recyclerView.setAdapter(wordStudyAdapter);
        loadData();//加载数据
        wordStudyAdapter.setItemListener(new WordStudyAdapter.ItemListener() {
            @Override
            public void ukPhoneClick(Word word) {
                playWord(word);
            }

            @Override
            public void usPhoneClick(Word word) {
                usPlayWord(word);
            }

            @Override
            public void titleClick(Word word) {
                playWord(word);
            }
        });
        // 设置上一个按钮点击事件
        preWord.setOnClickListener(v -> {
            // 获取上一个单词
            // this.currentWordIndex -= 1;
            String currentAndTotalText = (currentWordIndex + 1) + " / " + wordList.size();
            if (currentWordIndex == 0) {
                // 如果当前是第一个单词，直接禁用按钮
                MessageUtils.show("没有上一个了", myActivity);
                this.currentWordIndex = 0;
                Word currentWord = wordList.get(this.currentWordIndex);
                playWord(wordList.get(this.currentWordIndex));
                mTitleBar.setTitle(currentAndTotalText);
                Map<String, String> collectRequestParam = new HashMap<>();
                collectRequestParam.put("word", currentWord.getWord());
                // 调用 API 客户端的方法
                HttpUtils.sendGetRequest("/getCollectList", collectRequestParam, myActivity, Collect.class, collectResponse -> {
                    List<Collect> collectList = collectResponse.getDataList();
                    collect.setVisibility(!collectList.isEmpty() ? View.GONE : View.VISIBLE);
                    collect1.setVisibility(!collectList.isEmpty() ? View.VISIBLE : View.GONE);
                });
                wordStudyAdapter.setCurrentWord(currentWord, myActivity);
            } else {
                nextWord.setText("下一个");
                this.currentWordIndex -= 1;
                Word currentWord = wordList.get(this.currentWordIndex);
                playWord(currentWord);
                mTitleBar.setTitle(currentAndTotalText);
                Map<String, String> collectRequestParam = new HashMap<>();
                collectRequestParam.put("word", currentWord.getWord());
                // 调用 API 客户端的方法
                HttpUtils.sendGetRequest("/getCollectList", collectRequestParam, myActivity, Collect.class, collectResponse -> {
                    List<Collect> collectList = collectResponse.getDataList();
                    collect.setVisibility(!collectList.isEmpty() ? View.GONE : View.VISIBLE);
                    collect1.setVisibility(!collectList.isEmpty() ? View.VISIBLE : View.GONE);
                    wordStudyAdapter.setCurrentWord(currentWord, myActivity);
                });

            }
        });
        // 设置下一个按钮点击事件
        nextWord.setOnClickListener(v -> {
            // 先将当前单词保存到已学习列表

            // 获取下一个单词
            this.currentWordIndex += 1;
            String currentAndTotalText = (currentWordIndex + 1) + " / " + wordList.size();
            if (currentWordIndex == wordList.size()) {
                // 如果当前是最后一个单词，直接退出页面
                if (true) {
                    // 调用 API 客户端的方法
                    HttpUtils.sendGetRequest("/getUserStudyPlan", new HashMap<>(), myActivity, StudyPlan.class, response -> {
                        // 加载当前用户学习情况 dayTask,todayCount,totalCount, currentUserDict;
                        StudyPlan studyPlan = response.getData();

                        String message = String.format("您今日已学习%s个单词，继续加油噢！", studyPlan.getTodayCount());
                        sendNotify(message, myActivity);
                    });
                }
                finish();
            } else if (currentWordIndex == (wordList.size() - 1)) {
                Word currentWord = wordList.get(this.currentWordIndex);
                // 如果下一个单词是最后一个，显示学习完成按钮
                nextWord.setText("完成学习");
                playWord(currentWord);
                mTitleBar.setTitle(currentAndTotalText);
                Map<String, String> collectRequestParam = new HashMap<>();
                collectRequestParam.put("word", currentWord.getWord());
                // 调用 API 客户端的方法
                HttpUtils.sendGetRequest("/getCollectList", collectRequestParam, myActivity, Collect.class, collectResponse -> {
                    List<Collect> collectList = collectResponse.getDataList();
                    collect.setVisibility(!collectList.isEmpty() ? View.GONE : View.VISIBLE);
                    collect1.setVisibility(!collectList.isEmpty() ? View.VISIBLE : View.GONE);
                });
                wordStudyAdapter.setCurrentWord(currentWord, myActivity);
            } else {
                Word currentWord = wordList.get(this.currentWordIndex);
                nextWord.setText("下一个");
                playWord(currentWord);
                mTitleBar.setTitle(currentAndTotalText);
                Map<String, String> collectRequestParam = new HashMap<>();
                collectRequestParam.put("word", currentWord.getWord());
                // 调用 API 客户端的方法
                HttpUtils.sendGetRequest("/getCollectList", collectRequestParam, myActivity, Collect.class, collectResponse -> {
                    List<Collect> collectList = collectResponse.getDataList();
                    collect.setVisibility(!collectList.isEmpty() ? View.GONE : View.VISIBLE);
                    collect1.setVisibility(!collectList.isEmpty() ? View.VISIBLE : View.GONE);
                });
                wordStudyAdapter.setCurrentWord(currentWord, myActivity);
            }
        });

        //收藏
        collect.setOnClickListener(v -> {
            Map<String, String> requestParam = new HashMap<>();
            requestParam.put("word", wordList.get(currentWordIndex).getWord());
            // 调用 API 客户端的方法
            HttpUtils.sendGetRequest("/collectWord", requestParam, myActivity, Browse.class, response -> {
                MessageUtils.show("收藏成功", myActivity);
                collect.setVisibility(View.GONE);
                collect1.setVisibility(View.VISIBLE);
            });
        });
        //取消
        collect1.setOnClickListener(v -> {
            Map<String, String> requestParam = new HashMap<>();
            requestParam.put("word", wordList.get(currentWordIndex).getWord());
            // 调用 API 客户端的方法
            HttpUtils.sendGetRequest("/cancelCollectWord", requestParam, myActivity, Browse.class, response -> {
                MessageUtils.show("取消成功", myActivity);
                collect.setVisibility(View.VISIBLE);
                collect1.setVisibility(View.GONE);
            });
        });
    }

    /**
     * 加载数据
     */
    private void loadData() {
        // 接受前页面传来的单词列表
        Serializable serializableExtra = getIntent().getSerializableExtra("wordArray");
        Serializable serializableExtraDict = getIntent().getSerializableExtra("dict");
        if (serializableExtra == null || serializableExtraDict == null) {
            MessageUtils.show("未查询到当前词汇您可学习的单词", myActivity);
            finish();
            return;
        }

        String[] wordArray = (String[]) serializableExtra;

        if (wordArray.length < 1) {
            MessageUtils.show("未查询到当前词汇您可学习的单词", myActivity);
            finish();
            return;
        }

        StringBuilder wordsWhere = new StringBuilder();
        for (String word : wordArray) {
            wordsWhere.append(word).append(",");
        }
        String wordListStr = wordsWhere.toString().substring(0, wordsWhere.toString().length() - 1);
        Map<String, String> requestParam = new HashMap<>();
        requestParam.put("wordList", wordListStr);
        // 调用 API 客户端的方法
        HttpUtils.sendGetRequest("/getWordList", requestParam, myActivity, Word.class, response -> {
            wordList  = response.getDataList();
            if (wordList.size() == 1) {
                nextWord.setText("完成学习");
            }
            mTitleBar.setTitle((currentWordIndex + 1) + " / " + wordList.size());

            Word currentWord = wordList.get(currentWordIndex);

            Map<String, String> collectRequestParam = new HashMap<>();
            collectRequestParam.put("word", currentWord.getWord());
            // 调用 API 客户端的方法
            HttpUtils.sendGetRequest("/getCollectList", collectRequestParam, myActivity, Collect.class, collectResponse -> {
                List<Collect> collectList = collectResponse.getDataList();
                collect.setVisibility(!collectList.isEmpty() ? View.GONE : View.VISIBLE);
                collect1.setVisibility(!collectList.isEmpty() ? View.VISIBLE : View.GONE);
            });

            playWord(currentWord);
            wordStudyAdapter.setCurrentWord(currentWord, myActivity);
        });
    }

    // 播放单词
    private void playWord(Word word) {
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
            mediaPlayer = new MediaPlayer();
        } else
            mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(CommonUtils.wordSingUrl + word.getWord());
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                }
            });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                }
            });
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    MessageUtils.show("发生错误，请检查网络设置", myActivity);
                    onBackPressed();
                    return true;
                }
            });
        } catch (Exception e) {
            com.example.word.util.ExceptionUtils.printExceptionDetail(e);
        }
    }

    // 美式播放单词
    private void usPlayWord(Word word) {
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
            mediaPlayer = new MediaPlayer();
        } else
            mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource("https://dict.youdao.com/dictvoice?type=0&audio=" + word.getWord());
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                }
            });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                }
            });
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    MessageUtils.show("发生错误，请检查网络设置", myActivity);
                    onBackPressed();
                    return true;
                }
            });
        } catch (Exception e) {
            com.example.word.util.ExceptionUtils.printExceptionDetail(e);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void sendNotify(String message, Context context) {
        StudyPlan studyPlan;// 创建通知渠道（仅适用于 Android 8.0 及以上）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("channel_id", "Channel Name", NotificationManager.IMPORTANCE_DEFAULT);
            channel.setDescription("Channel Description");
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }

        // 创建通知
        Notification.Builder builder = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            builder = new Notification.Builder(context, "channel_id")
                    .setSmallIcon(R.drawable.a1)
                    .setContentTitle("学习通知")
                    .setContentText(message)
                    .setPriority(Notification.PRIORITY_DEFAULT);
        }

        // 使用通知管理器显示通知
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.notify((int) Math.floor(Math.random() * 10), builder.build());
    }

    @Override
    public void onResume() {
        super.onResume();
    }
}